package com.dwyinyuan.domain.aggregate_user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.*;
import com.baomidou.mybatisplus.core.metadata.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.*;
import com.dwyinyuan.domain.aggregate_user.entity.*;
import com.dwyinyuan.domain.aggregate_user.service.*;
import com.dwyinyuan.domain.aggregate_user.repository.mapper.*;
import com.dwyinyuan.infrastructure.util.utils.*;
import com.dwyinyuan.interfaces.dto.*;
import com.github.dozermapper.core.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;

import java.util.*;
import java.util.stream.*;

/**
 * 微信公众号：笛舞音缘
 * <p>
 * 用户服务实现类
 * <p>
 * Created by andy  on 2020-12-16.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private Mapper mapper;

    @Override
    public int save(UserDTO userDTO) {

        //com.github.dozermapper.core.Mapper 深度copy工具
        UserDO userDO = mapper.map(userDTO, UserDO.class);
        return userMapper.insert(userDO);
    }

    @Override
    public int update(Long id, UserDTO userDTO) {

        UserDO userDO = mapper.map(userDTO, UserDO.class);
        userDO.setId(id);

        return userMapper.updateById(userDO);
    }

    @Override
    public int delete(Long id) {
        return userMapper.deleteById(id);
    }

    @Override
    public PageResult<List<UserDTO>> query(PageQuery<UserQueryDTO> pageQuery) {

        // 手动校验功能
        ValidatorUtils.validate(pageQuery);

        // 参数构造
        Page page = new Page(pageQuery.getPageNo(), pageQuery.getPageSize());

        UserDO query = mapper.map(pageQuery.getQuery(), UserDO.class);

        QueryWrapper queryWrapper = new QueryWrapper(query);

        // 查询
        IPage<UserDO> userDOIPage = userMapper.selectPage(page, queryWrapper);

        // 结果解析
        PageResult pageResult = new PageResult();
        pageResult.setPageNo((int) userDOIPage.getCurrent());
        pageResult.setPageSize((int) userDOIPage.getSize());
        pageResult.setTotal(userDOIPage.getTotal());
        pageResult.setPageNum(userDOIPage.getPages());

        // 对数据进行转换
        List<UserDTO> userDTOList = Optional.ofNullable(userDOIPage.getRecords())
                .map(List::stream)
                .orElseGet(Stream::empty)
                .map(userDO -> mapper.map(userDO, UserDTO.class))
                .collect(Collectors.toList());

        pageResult.setData(userDTOList);

        return pageResult;
    }
}
